package testmybatis.springmybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description 创建对象的工厂bean，每个mapper对应一个factorybean
 * @Author dangxianyue
 * @Date 2024/3/27 17:28
 */
// @Component
public class MyMybatisFactoryBean implements FactoryBean {

    private SqlSession sqlSession;

    private Class mapperClass;

    public MyMybatisFactoryBean(final Class mapperClass) {
        this.mapperClass = mapperClass;
    }

    // 通过构造方法注入
    // 1. 当只有一个构造方法时，就用它（可以没有@Autowired）
    // 2. 当有多个构造方法时，默认用无参构造方法，当没有无参构造方法并且又没有@Autowired指定使用哪个时会报错
    // public MyMybatisFactoryBean(final SqlSessionFactory sqlSessionFactory) {
    //     sqlSessionFactory.getConfiguration().addMapper(MemberMapper.class);
    //     this.sqlSession = sqlSessionFactory.openSession();
    // }


    // 通过set方法注入
    @Autowired
    public void setSqlSession(final SqlSessionFactory sqlSessionFactory) {
        // sqlSessionFactory.getConfiguration().addMapper(MemberMapper.class);
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
        this.sqlSession = sqlSessionFactory.openSession();
    }




    @Override
    public Object getObject() throws Exception {
        // mybatis产生Mapper接口的代理对象
        // return sqlSession.getMapper(MemberMapper.class);
        return sqlSession.getMapper(mapperClass);
    }

    @Override
    public Class<?> getObjectType() {
        // return MemberMapper.class;
        return mapperClass;
    }
}
